package org.cuit.lmq.lab;


import cn.hutool.core.util.ObjectUtil;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;

public class MemoryCacheBusinessTemplate {
    public static void main(String[] args) {
        Service service = new Service();
        // controller调用service
        service.execute();
    }

    static class Service {
        // key为id，value为信息
        private final RedisHelper<StaffInfo> redisHelper = new RedisHelper<>();

        Service() {
            this.init();
        }

        private void init() {
            // 用来模拟嵌套的数据
            redisHelper.setValue("123", new StaffInfo("一号员工", "456"));
            redisHelper.setValue("456", new StaffInfo("二号员工", "789"));
            redisHelper.setValue("789", new StaffInfo("三号员工", "789"));
        }

        public void execute() {
            // 进行查询，数据组装
            String baseId = "123";
            StaffInfo staffInfo = getPersistentObject(baseId);
            String leaderId = staffInfo.getParentId();
            System.out.println("staffInfo = " + staffInfo);

            StaffInfo leaderInfo = getPersistentObject(leaderId);
            String majorId = leaderInfo.getParentId();
            System.out.println("leaderInfo = " + leaderInfo);

            StaffInfo majorInfo = getPersistentObject(majorId);
            System.out.println("majorInfo = " + majorInfo);

            System.out.println(getPersistentObject("521"));

            redisHelper.allDataView();
        }

        private StaffInfo getPersistentObject(String userId) {
            // key就是构造好的方法，只给本方法内的方法调用
            StaffInfo staffInfo = redisHelper.getValue(userId);
            if (ObjectUtil.isNull(staffInfo)) {
                // 构造查询信息
                SearchParam param = new SearchParam();
                param.setQueryType(0);
                param.setUserId(userId);
                staffInfo = getDataByOpenFeign(param);
                redisHelper.setValue(userId, staffInfo);
            }
            return staffInfo;
        }

        private StaffInfo getDataByOpenFeign(SearchParam param) {
            // 使用feign查询，回返信息，此处使用param.toString()来模拟业务逻辑
            return new StaffInfo("熬过无人问津的日子，才能迎来鲜花和掌声, 我的Id是" + param.getUserId(), "000");
        }
    }
}

class RedisHelper<T> {
    private final Map<String, T> cache = new HashMap<>();

    public void setValue(String key, T value) {
        cache.put(key, value);
    }

    public T getValue(String key) {
        return cache.get(key);
    }

    public void allDataView() {
        System.out.println(cache);
    }
}

@Data
class SearchParam {
    private Integer queryType;

    private String userId;
}

@Data
@AllArgsConstructor
class StaffInfo {
    private String otherInfo;

    private String parentId;
}